<!DOCTYPE HTML>
<html lang="en">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="探究Vuex的使用和原理, Casey Lu&#39;s Blog">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>探究Vuex的使用和原理 | Casey Lu&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/medias/maozhao.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 4.2.0"><link rel="alternate" href="/atom.xml" title="Casey Lu's Blog" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Casey Lu's Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>Index</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>Tags</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>Categories</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>Archives</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>About</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="Search" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Casey Lu's Blog</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			Index
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			Tags
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			Categories
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			Archives
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			About
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('嘻嘻嘻，访问本文章需要密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误哦~');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/articleimages/14.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">探究Vuex的使用和原理</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Vue/">
                                <span class="chip bg-color">Vue</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                技术分享
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2020-03-11
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>Word Count:&nbsp;&nbsp;
                    2.2k
                </div>
                

                

                
            </div>

        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>在使用Vue框架的时候，经常会面临着组件间传值的问题，这时候就需要使用Vuex作为其状态管理器。</p>
<p>简单回顾一下，传统的Vue组件常用的通信的方式有：</p>
<ul>
<li><strong>父子通信:</strong> 父→子传值（<code>props</code>），子→父传值(<code>events($emit)</code>);父调用子方法<code>ref;provide/indect</code></li>
<li><strong>兄弟通信：</strong> <code>eventBus</code>中央事件总线，担任组件之间通信桥梁</li>
<li><strong>跨级嵌套通信：</strong> <code>bus</code>; <code>provide/indect</code>(Vue2.2 新增api)，bus机制同上，子组件绑定方法，触发时发布<code>eventBus</code>，每个子组件做订阅监控，触发在created里面的方法执行；<code>provide / inject</code> API 主要解决了跨级组件间的通信问题，不过它的使用场景，主要是子组件获取上级组件的状态，跨级组件间建立了一种主动提供与依赖注入的关系。<br>
（关于详细的常用组件通信方式介绍，之后会<img class="emoji" draggable="false" alt="✏️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/270f.png"/>写文章专门介绍~）</li>
</ul>
<p>在大型的复杂项目中，可能会存在着多级组件的嵌套，需要实现一个组件更改某个数据，多个组件便可以自动获取更改后的数据进行业务逻辑处理，这时就轮到今天的主角<strong>Vuex</strong>闪亮出场了。</p>
<h2 id="一、Vuex是什么？">一、Vuex是什么？</h2>
<p><a href="https://vuex.vuejs.org/zh/" target="_blank" rel="noopener">Vuex的介绍文档</a></p>
<p>Vuex就是一个专门为Vue.js应用程序开发的<strong>状态管理模式</strong>，类似于React中的Redux。</p>
<p><strong>Vuex的组成部分：</strong></p>
<ul>
<li><strong>state</strong>, 驱动应用的数据源</li>
<li><strong>view</strong>, 以声明的方式将state映射到视图</li>
<li><strong>actions</strong>,响应在view上的用户输入导致的状态变化</li>
</ul>
<p><img src="https://img-blog.csdnimg.cn/2020031114394775.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0ODczNzEw,size_16,color_FFFFFF,t_70" alt="“单向数据流”示意">当多个组件共享状态时，上述的单向数据流的简易性就会很容易被破坏：1）多个视图依赖于同一状态，来自不同视图的行为需要变更同一状态</p>
<p><strong>Vuex的设计思想：</strong><br>
借鉴了Flux、Redux,将数据存放到全局的store，再将<code>store</code>挂载到每个vue实例组件中，利用Vue.js的细粒度数据响应机制进行高效的状态更新</p>
<h2 id="二、Vuex的使用">二、Vuex的使用</h2>
<p><img src="https://img-blog.csdnimg.cn/20200311170108159.png" alt="Vuex的使用"></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">import Vuex from 'vuex';
Vue.use(Vuex); // 1.Vue的插件机制，安装Vuex
let store = new Vuex.Store({ // 2.实例化store,调用install方法
  state:{
    count: 1
  },
  getters,
  modules,
  mutations,
  actions,
  plugins
});
new Vue({ // 3.注入store,挂载Vue实例
  store,
  render: h => h(app)
}).$mount('#app')
</code></pre>
<p>Vuex只是一个状态管理器，存储的数据时<strong>响应式</strong>的，并不会保存，刷新之后就回到了初始的状态，如果想保存改变的数据，最好结合<code>LocalStorage</code>（需要注意，Vuex的数据都是以数组形式保存，而Localstorage只支持字符串，所以记得使用JSON转换：Array → String :  <code>JSON.stringify()</code> ；String → Array: <code>JSON.parse()</code>）</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">let defaultCity = "上海"
try{ // 用户关闭了本地存储，在外层加一个try...catch
  if(!defaultCity){
    defaultCity = JSON.parse(window.localStorage.getItem('defaultCity'))
  }
}catch(e){}

export default new Vuex.Store({
  state:{
    city: defaultCity
  },
  mutations:{
    changeCity(state, city){
      state.city = city
      try{
        window.localStorage.setItem('defaultCity', JSON.stringify(state.city))
        // 数据改变的时候拷贝一份到LocalStorage中
      }catch(e){}
    }
  }
})
</code></pre>
<h2 id="三、Vuex的原理">三、Vuex的原理</h2>
<p><img src="https://img-blog.csdnimg.cn/20200311152752656.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0ODczNzEw,size_16,color_FFFFFF,t_70" alt="Vuex的实现原理"><strong>1.Vuex的原理</strong>：<br>
Vuex实现了一个单向的数据流，在全局拥有一个State存放数据，当组件要更改State中的数据时，必须通过<code>Mutation</code>进行，<code>Mutation</code>同时提供了订阅者模式供外部插件调用获取State数据的更新。而当所有异步操作(常见于调用后端接口异步获取更新数据)或批量的同步操作需要走 <code>Action</code>，但 Action 也是无法直接修改 <code>State</code> 的，还是需要通过 <code>Mutation</code> 来修改 <code>State</code> 的数据。最后，根据 <code>State</code> 的变化，渲染到视图上。</p>
<p><strong>2.Vuex中各个模块的详细介绍</strong>：</p>
<ul>
<li><strong>State:页面状态管理容器</strong> 集中存储 Vue 组件中 data 对象的零散数据，全局唯一，以进行统一的状态管理。页面显示所需的数据从该对象中进行读取，利用 Vue 的<strong>细粒度数据响应机制</strong>来进行高效的状态更新。
<ul>
<li><code>getter()</code>: store的计算属性，state对象读取方法，包含在<code>render</code>中。Vue组件通过它读取全局state对象，getter返回的值会根据他的依赖被缓存起来，且只有当他的依赖值发生改变时才会被重新计算。</li>
</ul>
</li>
<li><strong>Actions: 操作行为处理模块</strong> 组件中的<code>$store.dispatch('action 名称'，data)</code>来触发,然后由commit()来触发mutation的调用，<strong>间接更新state</strong>（因此actions更像是一个装饰器，提交mutation但不直接变更state）。负责处理 Vue Components 接收到的所有交互行为。包含同步/异步操作，支持多个同名方法，按照注册的顺序依次触发。向后台 API 请求的操作就在这个模块中进行，包括触发其他 action 以及提交 mutation 的操作。该模块提供了 Promise 的封装，以支持 action 的链式触发。
<ul>
<li><code>dispatch()</code>: 操作行为触发方法，唯一能执行<code>action</code>的方法</li>
</ul>
</li>
<li><strong>Mutations: 状态改变操作方法</strong>由<code>actions</code>中的<code>commit('mutation 名称')</code>来触发。Vuex 修改 state 的唯一推荐方法。该方法只能进行同步操作，且方法名只能全局唯一。操作之中会有一些 hook 暴露出来，以进行 state 的监控等。
<ul>
<li><code>commit()</code>: 状态改变提交方法，唯一能执行<code>mutation</code>的方法 ，<code>store.commit()</code>更改state存储的状态</li>
</ul>
</li>
<li><strong>Module:store分割的模块</strong>：将store分成模块（modules）每个模块拥有自己的 <code>state、mutation、action、getter</code>、甚至是嵌套子模块——从上至下进行同样方式的分割，从而提升代码的可维护性</li>
</ul>
<p><img class="emoji" draggable="false" alt="🔸" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f538.png"/> action 类似于 mutation，区别在于：</p>
<ul>
<li>Action 提交的是 mutation，而不是直接变更状态。</li>
<li>Action 可以包含任意异步操作，而Mutation只能且必须是同步操作。</li>
</ul>
<p><strong>3.Vuex中两个重要的问题</strong>：</p>
<ul>
<li><img class="emoji" draggable="false" alt="❓" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2753.png"/> <code>store</code>如何挂载注入到组件中？</li>
<li><img class="emoji" draggable="false" alt="❓" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2753.png"/> <code>state</code>和<code>getters</code>如何映射到各个组件实例中响应式更新状态？</li>
</ul>
<p><strong>Q1：store挂载注入组件</strong></p>
<p>**A：**vuex是利用vue的mixin混入机制，在beforeCreate钩子前混入vuexInit方法，<code>vuexInit</code>方法实现了store注入vue组件实例，并注册了vuex store的引用属性$store。<br>
<img src="https://img-blog.csdnimg.cn/20200311171745139.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0ODczNzEw,size_16,color_FFFFFF,t_70" alt="store注入组件的过程"><br>
<strong>Q2：state和getters如何映射到组件实例中响应式更新状态</strong></p>
<p><strong>A：</strong> 通过分析源码中的resetStoreVM核心方法，可以发现：</p>
<ul>
<li>Vuex的state状态是响应式，是借助Vue的data是响应式，将state存入vue实例组件的data中</li>
<li>Vuex的getters则是借助Vue的计算属性computed来实现数据实时监听</li>
</ul>
<p>说了半天，Vuex还是比较适合逻辑偏复杂的应用，不然说实在难免会有些小题大做~</p>
<h2 id="四、Vuex的高级使用">四、Vuex的高级使用</h2>
<p><strong>场景：</strong> 点击某个地方选择城市，所有涉及到城市的地方都变化</p>
<p>安装vuex:  <code>npm install vuex --save</code></p>
<p>新建<code>src/store/index.js</code>，并在其中引用:<br>
<code>import Vue from 'vue'</code><br>
<code>import Vuex from 'vuex'</code></p>
<p><strong>基本使用示例：</strong></p>
<ol>
<li>某组件中触发状态改变的函数</li>
</ol>
<pre class=" language-language-javascript"><code class="language-language-javascript">handleClick = function(city){
  this.$store.commit('changeCity', city)
}
</code></pre>
<ol start="2">
<li>
<p>在store/index.js下面设置状态的改变<br>
为了易于管理和维护，分离开state,mutations</p>
<p>① store/index.js:</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  mutations
})
</code></pre>
<p>② store/state.js:</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">let defaultCity = '上海'
try {
  if (localStorage.city) {
    defaultCity = localStorage.city
  }
} catch (e) {}

export default {
  city: defaultCity
}
</code></pre>
<p>③ store/mutations.js：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">export default {
  changeCity (state, city) {
    state.city = city
    try {
      localStorage.city = city
    } catch (e) {}
  }
}

</code></pre>
</li>
<li>
<p>在组件中调用  <code>this.$store.state.city</code></p>
</li>
</ol>
<p><strong>高级使用示例：</strong></p>
<p>vuex还为我们提供了非常高级的api——<code>mapState、mapMutations、mapActions</code></p>
<p><code>mapState</code>——把vuex中的数据映射到组件的<code>computed</code>的计算属性中</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState(['city'])
  }
}
</code></pre>
<p>建立了这样的映射之后，组件中使用数据时的<code>this.$store.state.city</code>就可以替换为<code>this.city</code></p>
<p>除了数组的映射，还可以实现对象的映射,eg:</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">computed: {
  ...mapState({
    currentCity: 'city'
  })
}
</code></pre>
<p>调用只需要<code>this.currentCity</code></p>
<p>此外，还有简单的方法<code>mapMutations</code>，用法同<code>mapState</code><br>
<code>import { mapState, mapMutations } from 'vuex'</code></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">methods: {
  handleCityClick (city) {
    // dispatch派发一个名字为changeCity的action,配合vuex中的actions
    // this.$store.commit('changeCity', city)
    this.changeCity(city) // 使用mapMutations之后可以这样调用
    this.$router.push('/')
  },
  ...mapMutations(['changeCity'])
},
</code></pre>
<p>对于功能复杂的应用，可以使用<code>Mudules</code>对代码进行拆分，实现vuex的高级使用</p>
<blockquote>
<p>作为状态管理工具，Vuex采用集中式储存管理应用的所有组件的状态，并以相应的规则保证状态以一种可预测的方式发生变换</p>
</blockquote>
<p><img class="emoji" draggable="false" alt="📝" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4dd.png"/>Vuex并没有限制代码结构，但是，规定了一些需要遵守的规则：</p>
<p>1）应用层级的状态应该集中到单个的store对象中<br>
2）提交 mutation是更改状态的唯一方法，并且这个过程是同步的<br>
3）异步逻辑都应该封装到action里面</p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        Author:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io" rel="external nofollow noreferrer">Casey Lu</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        Link:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io/2020/03/11/11-tan-jiu-vuex-de-shi-yong-he-yuan-li/">https://caseylu.gitee.io/2020/03/11/11-tan-jiu-vuex-de-shi-yong-he-yuan-li/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        Reprint policy:
                    </i>
                </span>
                <span class="reprint-info">
                    All articles in this blog are used except for special statements
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    reprint polocy. If reproduced, please indicate source
                    <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>Copied successfully, please follow the reprint policy of this article</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">more</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Vue/">
                                    <span class="chip bg-color">Vue</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">谢谢大佬的小鱼干，喵~</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b739596984975414aa79',
        clientSecret: 'c5792bc3376f951910111f232176fbadfa919286',
        repo: 'L0ittle.github.io',
        owner: 'L0ittle',
        admin: "L0ittle",
        id: '2020-03-11T18-14-40',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/2020/03/12/12-qian-tan-node-de-san-liang-shi/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/31.jpg" class="responsive-img" alt="浅谈Node的两三事">
                        
                        <span class="card-title">浅谈Node的两三事</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            大多数情况下，我们所见的Javascript是运行在浏览器中的，而事实上，JS是一门&quot;完整&quot;的语言,浏览器只是提供给了它一个上下文。Node.js实际上也是一种上下文，它允许在后端运行JS代码。
针对Node的总结，cc
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-12
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                    技术分享
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Node/">
                        <span class="chip bg-color">Node</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/03/10/10-javascript-zhong-de-bi-bao-closure/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/38.jpg" class="responsive-img" alt="Javascript中的闭包Closure">
                        
                        <span class="card-title">Javascript中的闭包Closure</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            对JS中的闭包还没有了解过的可看 MDN 闭包， 在面试的时候闭包也是经常被提及的Topic
一、闭包的概念
简单的说，闭包就是有权访问其他函数作用域内部变量的函数
闭包 = 函数 + 函数能够访问的自由变量
闭包的三个特点：

函数嵌套函
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-10
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                    技术分享
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Javascript/">
                        <span class="chip bg-color">Javascript</span>
                    </a>
                    
                    <a href="/tags/%E9%97%AD%E5%8C%85/">
                        <span class="chip bg-color">闭包</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('100')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + 'From: Casey Lu&#39;s Blog<br />'
            + 'Author: Casey Lu<br />'
            + 'Link: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="4892766072"
                   fixed='true'
                   autoplay='false'
                   theme:='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2020</span>
            <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">63.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/L0ittle" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:caseylu119@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1351238945" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1351238945" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
